﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Helpers;

namespace DataProcessModule.Protocol
{
    class CarCurrentStats : BaseInstruction
    {
        #region param

        private CarControlInfo CarControlStats;

        private PowerSupplyInfo PowerSupplyStats;

        private ShiftingGearInfo GearShiftingStats;

        private BatteriesInfo DeviceBatteriesStats;

        #endregion

        #region attributes

        public CarControlInfo InfoCarControl { get { return CarControlStats; } }

        public PowerSupplyInfo InfoPowerSupply { get { return PowerSupplyStats; } }

        public ShiftingGearInfo InfoShiftingGear { get { return GearShiftingStats; } }

        public BatteriesInfo InfoBatteries { get { return DeviceBatteriesStats; } }

        #endregion

        #region construction

        public CarCurrentStats()
        {
            instHeadInfo.instID = 0x0112;
        }
        public CarCurrentStats(byte[] buf)
        {
            CarControlStats = new CarControlInfo();
            PowerSupplyStats = new PowerSupplyInfo();
            GearShiftingStats = new ShiftingGearInfo();
            DeviceBatteriesStats = new BatteriesInfo();

            int offset = 0;
            // 获取头信息
            GetHeadInfo(buf, ref offset);
            BodyStreamSplit(buf, ref offset);
        }

        #endregion

        #region function

        public void BodyStreamSplit(byte[] buf, ref int offset)
        {
            try
            {
                CarControlStats.Currentspeed = (float)BC.ToUInt16Net(buf, ref offset)/(float)10.0;
                CarControlStats.TotalDistance = (double)BC.ToUInt32Net(buf, ref offset)/(double)10.0;
                ShiftingGearBitConv(buf[offset++]);
                CarControlStats.AcceleratorDegree = buf[offset++];
                CarControlStats.BrakeDegree = buf[offset++];
                PowerSupplyStats.ChargingState = buf[offset++];
                PowerSupplyStats.ElectricityPowerControlTempratureLeft = buf[offset++];
                PowerSupplyStats.ElectricityPowerControlTempratureRight = buf[offset++];
                PowerSupplyStats.ElectricityPowerSpiningSpeedLeft = BC.ToUInt16Net(buf, ref offset);
                PowerSupplyStats.ElectricityPowerSpiningSpeedRight = BC.ToUInt16Net(buf, ref offset);
                PowerSupplyStats.ElectricityPowerTempratureLeft = buf[offset++];
                PowerSupplyStats.ElectricityPowerTempratureRight = buf[offset++];
                PowerSupplyStats.ElectricityPowerVoltageLeft = BC.ToInt16Net(buf, ref offset);
                PowerSupplyStats.ElectricityPowerVoltageRight = BC.ToInt16Net(buf, ref offset);
                PowerSupplyStats.ElecricityPowerDirectCurrentLeft = (float)BC.ToInt16Net(buf, ref offset) / (float)10.0;
                PowerSupplyStats.ElecricityPowerDirectCurrentRight = (float)BC.ToInt16Net(buf, ref offset) / (float)10.0;
                CarControlStats.AirConditionerTemprature = buf[offset++];
                DeviceBatteriesStats.MaxMotorBatterySequence = buf[offset++];
                DeviceBatteriesStats.MaxSingleBatterySequence = buf[offset++];
                DeviceBatteriesStats.SingleBatteryMaxVoltage = (float)BC.ToInt16Net(buf, ref offset)/(float)1000.0;
                DeviceBatteriesStats.MinMotorBatterySequence = buf[offset++];
                DeviceBatteriesStats.MinSingleBatterySequence = buf[offset++];
                DeviceBatteriesStats.SingleBatteryMinVoltage = (float)BC.ToInt16Net(buf, ref offset) / (float)1000.0;
                DeviceBatteriesStats.MaxTempratureMotorBatterySequence = buf[offset++];
                DeviceBatteriesStats.MaxTempratureProbeSequence = buf[offset++];
                DeviceBatteriesStats.MaxTemprature = buf[offset++];
                DeviceBatteriesStats.MinTempratureMotorBatterySequence = buf[offset++];
                DeviceBatteriesStats.MinTempratureProbeSequence = buf[offset++];
                DeviceBatteriesStats.MinTemprature = buf[offset++];
                DeviceBatteriesStats.TotalVoltage = (float)BC.ToInt16Net(buf, ref offset) / (float)10.0;
                DeviceBatteriesStats.TotalCurrent = (float)BC.ToInt16Net(buf, ref offset) / (float)10.0;
                DeviceBatteriesStats.SOC = (float)buf[offset++]/(float)2.5;
                DeviceBatteriesStats.CapablePower = (float)BC.ToInt16Net(buf, ref offset) / (float)10.0;
                DeviceBatteriesStats.BatteryInsulationResistance = buf[offset++];
                CarControlStats.InsideTemprature = buf[offset++];
                CarControlStats.OutsideTemprature = buf[offset++];
                CarControlStats.FrontBrakePressure = (float)buf[offset++] / (float)100.0;
                CarControlStats.BackBrakePressure = (float)buf[offset++] / (float)100.0;
                CarControlStats.MidBrakePressure = (float)buf[offset++] / (float)100.0;
                CarControlStats.ParkingBrakePressure = (float)buf[offset++] / (float)100.0;
                CarControlStats.AveragePowerConsumption = BC.ToInt16Net(buf, ref offset);
                CarControlStats.HundredKMPowerConsumption = BC.ToInt16Net(buf, ref offset);
            }
            catch (Exception e) { }
        }

        public string CombinedSqlString()
        {
            string _sql = string.Empty;
            _sql = "INSERT INTO table_firebox_car_state (TerminalKey" +
               ",CurrentSpeed,TotalDistance,GearShifting,AccelerationCapable,BrakeCapable,AccelerationValue" +
               ",BrakeValue,ChargeState,PowerSupplyControllerTemperatureLeft,PowerSupplyControllerTemperatureRight" +
               ",SpiningSpeedLeft,SpiningSpeedRight,PowerSupplyTempratureLeft,PowerSupplyTempratureRight" +
               ",MotorVoltageLeft,MotorVoltageRight,MotorCurrentLeft,MotorCurrentRight" +
               ",AirConditioningTemperature,MaximumPowerBatteryPackId" +
               ",MaximumBatterySerialId,MaximumSingleBatteryVoltage" +
               ",MinimumPowerBatteryPackId,MinimumBatterySerialId" +
               ",MinimumSingleBatteryVoltage,MaximumTemperaturePowerBatteryPackId" +
               ",MaximumProbeTempratureSequence,MaximumTemperatureValue" +
               ",MinimumTemperaturePowerBatteryPackId,MinimumProbeTempratureSequence" +
               ",MinimumTemperatureValue,TotalVoltage,TotalCurrent,SOC,RemainingEnergy" +
               ",BatteryInsulationResistance) VALUES ('" + instHeadInfo.tdPhoneNumber + "'," +
               CarControlStats.Currentspeed + ',' + CarControlStats.TotalDistance + ",'" +
               GearShiftingStats.GearPosition + "'," + GearShiftingStats.AcceleratorState + ',' +
               GearShiftingStats.BrakeState + ',' + CarControlStats.AcceleratorDegree + ',' +
               CarControlStats.BrakeDegree + ',' + PowerSupplyStats.ChargingState + ',' +
               PowerSupplyStats.ElectricityPowerControlTempratureLeft + ',' + PowerSupplyStats.ElectricityPowerControlTempratureRight + ',' +
               PowerSupplyStats.ElectricityPowerSpiningSpeedLeft + ',' + PowerSupplyStats.ElectricityPowerSpiningSpeedRight + ',' +
               PowerSupplyStats.ElectricityPowerTempratureLeft + ',' + PowerSupplyStats.ElectricityPowerTempratureRight + ',' +
               PowerSupplyStats.ElectricityPowerVoltageLeft + ',' + PowerSupplyStats.ElectricityPowerVoltageRight + ',' +
               PowerSupplyStats.ElecricityPowerDirectCurrentLeft + ',' + PowerSupplyStats.ElecricityPowerDirectCurrentRight + ',' +
               CarControlStats.AirConditionerTemprature + ',' + DeviceBatteriesStats.MaxMotorBatterySequence + ',' +
               DeviceBatteriesStats.MaxSingleBatterySequence + ',' + DeviceBatteriesStats.SingleBatteryMaxVoltage + ',' +
               DeviceBatteriesStats.MinMotorBatterySequence + ',' + DeviceBatteriesStats.MinSingleBatterySequence + ',' +
               DeviceBatteriesStats.SingleBatteryMinVoltage + ',' + DeviceBatteriesStats.MaxTempratureMotorBatterySequence + ',' +
               DeviceBatteriesStats.MaxTempratureProbeSequence + ',' + DeviceBatteriesStats.MaxTemprature + ',' +
               DeviceBatteriesStats.MinTempratureMotorBatterySequence + ',' + DeviceBatteriesStats.MinTempratureProbeSequence + ',' +
               DeviceBatteriesStats.MinTemprature + ',' + DeviceBatteriesStats.TotalVoltage + ',' +
               DeviceBatteriesStats.TotalCurrent + ',' + DeviceBatteriesStats.SOC + ',' +
               DeviceBatteriesStats.CapablePower + ',' + DeviceBatteriesStats.BatteryInsulationResistance  +
               ") ON DUPLICATE KEY UPDATE CurrentSpeed=VALUES(CurrentSpeed)" +
               ",GearShifting=VALUES(GearShifting),AccelerationCapable=VALUES(AccelerationCapable)" +
               ",BrakeCapable=VALUES(BrakeCapable),AccelerationValue=VALUES(AccelerationValue)" +
               ",TotalDistance=VALUES(TotalDistance),BrakeValue=VALUES(BrakeValue),ChargeState=VALUES(ChargeState)" +
               ",PowerSupplyControllerTemperatureLeft=VALUES(PowerSupplyControllerTemperatureLeft)" +
               ",PowerSupplyControllerTemperatureRight=VALUES(PowerSupplyControllerTemperatureRight)" +
               ",SpiningSpeedLeft=VALUES(SpiningSpeedLeft),SpiningSpeedRight=VALUES(SpiningSpeedRight)" +
               ",PowerSupplyTempratureLeft=VALUES(PowerSupplyTempratureLeft),PowerSupplyTempratureRight=VALUES(PowerSupplyTempratureRight)" +
               ",MotorVoltageLeft=VALUES(MotorVoltageLeft),MotorVoltageRight=VALUES(MotorVoltageRight)" +
               ",MotorCurrentLeft=VALUES(MotorCurrentLeft),MotorCurrentRight=VALUES(MotorCurrentRight)" +
               ",AirConditioningTemperature=VALUES(AirConditioningTemperature)" +
               ",MaximumPowerBatteryPackId=VALUES(MaximumPowerBatteryPackId)" +
               ",MaximumBatterySerialId=VALUES(MaximumBatterySerialId)" +
               ",MaximumSingleBatteryVoltage=VALUES(MaximumSingleBatteryVoltage)" +
               ",MinimumPowerBatteryPackId=VALUES(MinimumPowerBatteryPackId)" +
               ",MinimumBatterySerialId=VALUES(MinimumBatterySerialId)" +
               ",MinimumSingleBatteryVoltage=VALUES(MinimumSingleBatteryVoltage)" +
               ",MaximumTemperaturePowerBatteryPackId=VALUES(MaximumTemperaturePowerBatteryPackId)" +
               ",MaximumProbeTempratureSequence=VALUES(MaximumProbeTempratureSequence)" +
               ",MaximumTemperatureValue=VALUES(MaximumTemperatureValue)" +
               ",MinimumTemperaturePowerBatteryPackId=VALUES(MinimumTemperaturePowerBatteryPackId)" +
               ",MinimumProbeTempratureSequence=VALUES(MinimumProbeTempratureSequence)" +
               ",MinimumTemperatureValue=VALUES(MinimumTemperatureValue)" +
               ",TotalVoltage=VALUES(TotalVoltage),TotalCurrent=VALUES(TotalCurrent)" +
               ",SOC=VALUES(SOC),RemainingEnergy=VALUES(RemainingEnergy)" +
               ",BatteryInsulationResistance=VALUES(BatteryInsulationResistance);";
            return _sql;
        }
        public string InsertString()
        {
            string _sql = string.Empty;
            _sql = _sql = "INSERT INTO table_firebox_car_state_" + DateTime.Now.ToString("yyyyMMdd") + "(TerminalKey" +
               ",ReceivedTime,CurrentSpeed,TotalDistance,GearShifting,AccelerationCapable,BrakeCapable,AccelerationValue" +
               ",BrakeValue,ChargeState,PowerSupplyControllerTemperatureLeft,PowerSupplyControllerTemperatureRight" +
               ",SpiningSpeedLeft,SpiningSpeedRight,PowerSupplyTempratureLeft,PowerSupplyTempratureRight" +
               ",MotorVoltageLeft,MotorVoltageRight,MotorCurrentLeft,MotorCurrentRight" +
               ",AirConditioningTemperature,MaximumPowerBatteryPackId" +
               ",MaximumBatterySerialId,MaximumSingleBatteryVoltage" +
               ",MinimumPowerBatteryPackId,MinimumBatterySerialId" +
               ",MinimumSingleBatteryVoltage,MaximumTemperaturePowerBatteryPackId" +
               ",MaximumProbeTempratureSequence,MaximumTemperatureValue" +
               ",MinimumTemperaturePowerBatteryPackId,MinimumProbeTempratureSequence" +
               ",MinimumTemperatureValue,TotalVoltage,TotalCurrent,SOC,RemainingEnergy" +
               ",BatteryInsulationResistance,InsideTemprature,OutsideTemprature,FrontBrakePressure,BackBrakePressure,MidBrakePressure,ParkingBrakePressure,AveragePowerConsumption,HundredKMPowerConsumption) VALUES ('" + 
               instHeadInfo.tdPhoneNumber + "','" + DateTime.Now.ToString("yy-MM-dd HH:mm:ss") + "'," +
               CarControlStats.Currentspeed + ',' + CarControlStats.TotalDistance + ",'" +
               GearShiftingStats.GearPosition + "'," + GearShiftingStats.AcceleratorState + ',' +
               GearShiftingStats.BrakeState + ',' + CarControlStats.AcceleratorDegree + ',' +
               CarControlStats.BrakeDegree + ',' + PowerSupplyStats.ChargingState + ',' +
               PowerSupplyStats.ElectricityPowerControlTempratureLeft + ',' + PowerSupplyStats.ElectricityPowerControlTempratureRight + ',' +
               PowerSupplyStats.ElectricityPowerSpiningSpeedLeft + ',' + PowerSupplyStats.ElectricityPowerSpiningSpeedRight + ',' +
               PowerSupplyStats.ElectricityPowerTempratureLeft + ',' + PowerSupplyStats.ElectricityPowerTempratureRight + ',' +
               PowerSupplyStats.ElectricityPowerVoltageLeft + ',' + PowerSupplyStats.ElectricityPowerVoltageRight + ',' +
               PowerSupplyStats.ElecricityPowerDirectCurrentLeft + ',' + PowerSupplyStats.ElecricityPowerDirectCurrentRight + ',' +
               CarControlStats.AirConditionerTemprature + ',' + DeviceBatteriesStats.MaxMotorBatterySequence + ',' +
               DeviceBatteriesStats.MaxSingleBatterySequence + ',' + DeviceBatteriesStats.SingleBatteryMaxVoltage + ',' +
               DeviceBatteriesStats.MinMotorBatterySequence + ',' + DeviceBatteriesStats.MinSingleBatterySequence + ',' +
               DeviceBatteriesStats.SingleBatteryMinVoltage + ',' + DeviceBatteriesStats.MaxTempratureMotorBatterySequence + ',' +
               DeviceBatteriesStats.MaxTempratureProbeSequence + ',' + DeviceBatteriesStats.MaxTemprature + ',' +
               DeviceBatteriesStats.MinTempratureMotorBatterySequence + ',' + DeviceBatteriesStats.MinTempratureProbeSequence + ',' +
               DeviceBatteriesStats.MinTemprature + ',' + DeviceBatteriesStats.TotalVoltage + ',' +
               DeviceBatteriesStats.TotalCurrent + ',' + DeviceBatteriesStats.SOC + ',' +
               DeviceBatteriesStats.CapablePower + ',' + DeviceBatteriesStats.BatteryInsulationResistance + ',' +
               CarControlStats.InsideTemprature + ',' + CarControlStats.OutsideTemprature + ',' +
               CarControlStats.FrontBrakePressure + ',' + CarControlStats.BackBrakePressure + ',' +
               CarControlStats.MidBrakePressure + ',' + CarControlStats.ParkingBrakePressure + ',' +
               CarControlStats.AveragePowerConsumption + ',' + CarControlStats.HundredKMPowerConsumption + ");";
            return _sql;
        }
        public void ShiftingGearBitConv(byte _bits)
        {
            GearShiftingStats.AcceleratorState = BC.ReadBit(_bits, 5) == true ? 1 : 0;
            GearShiftingStats.BrakeState = BC.ReadBit(_bits, 4) == true ? 1 : 0;
            _bits %= 32;
            _bits %= 16;
            switch (_bits)
            {
                case 0x0:
                    GearShiftingStats.GearPosition = "NEUTRAL";
                    break;
                case 0x1:
                    GearShiftingStats.GearPosition = "1stGear";
                    break;
                case 0x2:
                    GearShiftingStats.GearPosition = "2ndGear";
                    break;
                case 0x3:
                    GearShiftingStats.GearPosition = "3rdGear";
                    break;
                case 0x4:
                    GearShiftingStats.GearPosition = "4thGear";
                    break;
                case 0x5:
                    GearShiftingStats.GearPosition = "5thGear";
                    break;
                case 0x6:
                    GearShiftingStats.GearPosition = "6thGear";
                    break;
                case 0xd:
                    GearShiftingStats.GearPosition = "PARKING";
                    break;
                case 0xe:
                    GearShiftingStats.GearPosition = "REVERSE";
                    break;
                case 0xf:
                    GearShiftingStats.GearPosition = "AUTOMATIC";
                    break;
                default:
                    GearShiftingStats.GearPosition = "UNKNOWN";
                    break;

            }
        }

        #endregion
    }

    #region structs

    [Serializable]
    public struct BatteriesInfo
    {
        public int MaxMotorBatterySequence;//最高电压动力蓄电池包序号	1	BYTE	有效值范围：1~255

        public int MaxSingleBatterySequence;//最高电压单体蓄电池序号	1	BYTE	有效值范围：1~255

        public float SingleBatteryMaxVoltage;//电池单体电压最高值	2	WORD	有效值范围：0~15000单位：0.001V

        public int MinMotorBatterySequence;//最低电压动力蓄电池包序号	1	BYTE	有效值范围：1~255

        public int MinSingleBatterySequence;//最低电压单体蓄电池序号	1	BYTE	有效值范围：1~255

        public float SingleBatteryMinVoltage;//电池单体电压最低值	2	WORD	有效值范围：0~15000单位：0.001V

        public int MaxTempratureMotorBatterySequence;//最高温度动力蓄电池包序号	1	BYTE	有效值范围：1~255

        public int MaxTempratureProbeSequence;//最高温度探针序号	1	BYTE	有效值范围：1~255

        public int MaxTemprature;//最高温度值	1	Signed BYTE	有效值范围：-40~+125单位：1℃

        public int MinTempratureMotorBatterySequence;//最低温度动力蓄电池包序号	1	BYTE	有效值范围：1~255

        public int MinTempratureProbeSequence;//最低温度探针序号	1	BYTE	有效值范围：1~255

        public int MinTemprature;//最低温度值	1	Signed BYTE	有效值范围：-40~+125单位：1℃

        public float TotalVoltage;//总电压	2	WORD	有效值范围：0~10000单位：0.1V

        public float TotalCurrent;//总电流	2	Signed WORD	有效值范围：-10000~+10000单位：0.1A

        public float SOC;//SOC	1	BYTE	有效值范围：0~250单位：0.4%

        public float CapablePower;//剩余能量	2	WORD	有效值范围：0~9999单位：0.1KWh

        public int BatteryInsulationResistance;//电池绝缘电阻	1	BYTE	有效值范围：0~255单位：1MΩ
    }

    [Serializable]
    public struct ShiftingGearInfo
    {
        public int BrakeState; //制动踏板有效 0：无效；1：有效

        public int AcceleratorState; //加速踏板有效 0：无效；1：有效 

        public string GearPosition;
        /*
        0000：空档         ……       
        0001：1档         1110：倒档
        0010：2档         1111：自动档
        0011：3档
        */
    }

    [Serializable]
    public struct PowerSupplyInfo
    {
        public int ChargingState;//充放电状态	1	BYTE	0x01：充电 0xff：放电

        public int ElectricityPowerControlTempratureLeft;//电机控制器温度（左）	1	Signed BYTE	有效值范围：-127~+127单位：1℃

        public int ElectricityPowerControlTempratureRight;//电机控制器温度（右）	1	Signed BYTE	有效值范围：-127~+127单位：1℃

        public uint ElectricityPowerSpiningSpeedLeft;//电机转速（左）	2	WORD	有效值范围：0~65536单位：1r/min

        public uint ElectricityPowerSpiningSpeedRight;//电机转速（右）	2	WORD	有效值范围：0~65536单位：1r/min

        public int ElectricityPowerTempratureLeft;//电机温度	（左） 1	 Signed BYTE	有效值范围：-127~127单位：1℃

        public int ElectricityPowerTempratureRight;//电机温度	（右） 1	Signed BYTE	有效值范围：-127~127单位：1℃

        public int ElectricityPowerVoltageLeft;//电机电压（左）	2	WORD	有效值范围：0~65535单位：1V

        public int ElectricityPowerVoltageRight;//电机电压（右）	2	WORD	有效值范围：0~65535单位：1V

        public float ElecricityPowerDirectCurrentLeft;//电机电流（左）	2	Signed BYTE	有效值范围：-10000~+10000单位：0.1A

        public float ElecricityPowerDirectCurrentRight;//电机电流	（右）2	Signed BYTE	有效值范围：-10000~+10000单位：0.1A
    }

    [Serializable]
    public struct CarControlInfo
    {
        public int AcceleratorDegree;//加速踏板行程值	1	BYTE	有效值范围：0~100单位：1%

        public int BrakeDegree;//制动踏板行程值	1	BYTE	有效值范围：0~100单位：1%

        public int AirConditionerTemprature;//空调温度	1	BYTE	有效值范围：0~255单位：1℃

        public float Currentspeed;//车速	2	WORD	有效值范围：0~2200单位：0.1km/h

        public double TotalDistance;//里程	4	DWORD	有效值范围：0~9999999单位：0.1km

        public int InsideTemprature;//室内温度 BYTE 1 有效值范围：-40~+125 单位：1℃

        public int OutsideTemprature;//室外温度	1	BYTE	有效值范围：-40~+125 单位：1℃

        public float FrontBrakePressure;//前制动气压值	1	BYTE	有效值范围：0~+120 单位：0.01Mpa

        public float BackBrakePressure;//后制动气压值	1	BYTE	有效值范围：0~+120 单位：0.01Mpa

        public float MidBrakePressure;//中制动气压值	1	BYTE	有效值范围：0~+120 单位：0.01Mpa

        public float ParkingBrakePressure;//驻车制动气压值	1	BYTE	有效值范围：0~+120 单位：0.01Mpa

        public int AveragePowerConsumption;//本次平均能耗	2	BYTE	有效值范围：0~+1000 单位：KWh/100KM

        public int HundredKMPowerConsumption;//最近百公里能耗	2	BYTE	有效值范围：0~+1000 单位：KWh/100KM
    }

    #endregion
}
